<template>
  <div class="yy-page yy-file-list">
    <div class="yy-page-search" v-if="showSearch">
      <WidgetForm ref="searchFormWidget" :option="{
        style: 'display: flex;',
        itemStyle: 'margin-right: 10px;margin-bottom: 0;align-items: center;'
      }" :form-fields="search.formFields" :form-buttons="search.formButtons" />
    </div>
    <div class="yy-page-header">
      <div class="yy-page-header_title">
        <el-button @click.stop="onOpenFolderModal()">新建目录</el-button>
        <el-button  type="primary" @click.stop="onOpenFileModal()">上传资源</el-button>
      </div>
      <div class="yy-page-header_action">
        <right-toolbar @showSearch="onShowSearch" @queryTable="getFileList"></right-toolbar>
      </div>
    </div>

    <div class="yy-page-header yy-file-list-header">
      <div class="yy-page-header_title">
        <template v-for="(folder, index) in folderArr" :key="folder.id">
          <a @click="onOpenFolder(folder)" :style="selectFolderId == folder.id ? 'color: #ccc;':''">{{folder.name}}</a>
          <span v-if="index < folderArr.length - 1" style="display: inline-block; padding: 0 5px; color: #ccc;">/</span>
        </template>
      </div>
    </div>
    <div class="yy-page-data yy-file-list-data">
      <WidgetTable
          ref="tableDataRef"
          :is-loading="table.isLoading"
          :columns="table.columns"
          :data="table.data"
          :options="table.options"
          :formats="table.formats"
          :paging-data="table.paging"
          @dblClickRow="onDblClickRow"
      >
        <template v-slot:fileName="{row, column}">
              <span style="font-size: 16px;">
                <span style="margin-right: 5px;"><el-icon v-if="row.category == 1"><Folder /></el-icon> <el-icon v-else><Document /></el-icon></span>
                <span>{{row[column.data]}}</span>
              </span>
        </template>
      </WidgetTable>
    </div>
    <FileModal ref="fileModalRef" :folderId="selectFolderId" @batchSaveFile="onBatchSaveFile"/>
    <FolderModal ref="folderModalRef" :folderId="selectFolderId" @saveSuccess="onCreateFolderSuccess"/>
  </div>
</template>
<script setup lang="ts">

import {onBeforeUnmount, reactive, ref, watch} from "vue";
import {formatDate, formatFileSize} from "@/utils/yayi.js";
import ResourceApi from "@/api/broadcast/resource";
import {ElButton, ElMessage} from "element-plus";
import FileModal from "@/views/broadcast/Resource/FileModal.vue";
import FolderModal from "@/views/broadcast/Resource/FolderModal.vue";
import WidgetTable from "@/components/widget/WidgetTable.vue";
import {TableColumn, WidgetFormField} from "@/model/Definition";
import {Folder, Document} from '@element-plus/icons-vue'
import {useRoute, useRouter} from "vue-router";
import {ResourceModel, ResourceStatusMap} from "@/model/ResourceModel";
import {PagingModel} from "@/model/PagingModel";
import WidgetForm from "@/components/widget/WidgetForm.vue";
import {BaseModel} from "@/model/BaseModel";
import {EmployeeModel} from "@/model/EmployeeModel";
import EmployeeApi from "@/api/system/empl";
import DepartSelector from "@/components/Business/DepartSelector.vue";
import useUserStore from "@/store/modules/user.js";

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const isLoading = ref<boolean>(false)
const fileModalRef = ref()
const folderModalRef = ref()
const folderArr = ref([])
const selectFolderId = ref<string>()
const selectFolder = ref<ResourceModel>()
const showSearch = ref(true)
const paging = ref<PagingModel<ResourceModel>>({total:0, pageIndex: 1, pageSize: 50, data:[]})
const search = reactive<{formFields: WidgetFormField[],formData: any, formButtons: any, modelInstance: BaseModel, searchApiFun:any}>({
  modelInstance: new EmployeeModel(),
  searchApiFun: EmployeeApi.listEmployee,
  formData: {
    deptId: userStore.deptId
  },
  formFields: [
    {field: 'deptId', initVal: () => userStore.deptId,  config: {select: {clearable: true}}, placeholder:'请选择科室', label: '所属科室', type: 'templateField', style:'width: 150px;', component: DepartSelector,
      atChange: ({deptId, depart}) => {
        search.formData.deptId = deptId
        getFileList()
      }},
    {field: 'searchKey', config: {input: {clearable: true}}, placeholder:"请输入关键字", label: '关键字', type: 'text', style:'width: 200px;',
      atChange: (searchKey) => {
        search.formData.searchKey = searchKey
        getFileList()
      }}
  ],
  formButtons: []
})
const searchFormWidget = ref()
const tableDataRef = ref()
const table = reactive<{
  isLoading: boolean,
  paging: any,
  columns: TableColumn[],
  data: ResourceModel[],
  options?: any,
  formats?: any
}>({
  isLoading: false,
  columns: [
    {
      "field":"fileName",
      "label":"名称",
      "showable":true,
      "minWidth": 200,
      "fixed": 'left',
    },
    {
      "field":"resourceType",
      "label":"文件类型",
      "showable":true,
      "minWidth": 200
    },
    {
      "field":"resourceName",
      "label":"描述",
      "showable":true,
      "minWidth": 200
    },
    {
      "field":"size",
      "label":"文件大小",
      "showable":true,
      "width": 140
    },
    {
      "field":"uploadedBy",
      "label":"创建者",
      "showable":true
    },
    {
      "field":"uploadedBy",
      "label":"创建时间",
      "showable":true,
      width: 160,
      "sortable":false
    },
    {
      "field":"resourceState",
      "label":"状态",
      "showable":true,
      width: 70,
      "fixed": 'right'
    },
    {
      "field":"action",
      "label":"操作",
      "width": 210,
      "showable":true,
      "sortable":false,
      "fixed": 'right'
    }
  ],
  paging: {
    isPaging: true,
    pageSize: 30,
    pageIndex: 1,
    total: 0,
    pageChange: (pageIndex: number) => {
      onPageChange(pageIndex)
    }
  },
  options: {
    highlight: true
  },
  data: [],
  formats: {
    'name': {
      slot: "fileName"
    },
    'category': {
      labelFormat: (val) => {
        return val === 1 ? '目录' : '文件'
      }
    },
    'dataSize': {
      labelFormat: (val, row) => {
        if (row.category === 1) {
          return ""
        }
        return formatFileSize(val)
      }
    },
    'createTime': {
      labelFormat:  (val) =>formatDate(val)
    },
    'resState': {
      textType:'text',
      typeFormat: (val, row) => {
        if (row.resCategory === 2) {
          return ResourceStatusMap.find(item => item.value === +val)?.type
        }
        return ''
      },
      labelFormat: (val, row) => {
        if (row.resCategory === 2) {
          return ResourceStatusMap.find(item => item.value === +val)?.label
        }
        return ''
      }
    },
    'action': {
      items: [
        {label: '预览', elType: 'button', condition: (row: ResourceModel) => row.resCategory === 2,  disabled: (row: ResourceModel) => +row.resState === 2, value: 'preview',  atClick: (data: ResourceModel) => {window.open(data.fullPath)}},
        {label: '重新转换', elType: 'button', condition: (row: ResourceModel) => row.resCategory === 2, disabled: (row: ResourceModel) => +row.resState === 2, value: 'translate',
          atClick: (data: ResourceModel) => {
            ResourceApi.translateResource(data.resId).then((res) => {
              data.resState = 2
              if (!listResStateTimeout) {
                listResStateTimeout = setTimeout(() => {
                  getFileList(table.paging.pageIndex)
                }, 10000)
              }
            })
          }
        },
        {label: '下载', elType: 'button', condition: (row: ResourceModel) => false && row.resCategory === 2, value: 'download',  atClick: (data: ResourceModel) => {window.open(data.resPath)}},
        {label: '打开', elType: 'button',condition: (row: ResourceModel) => row.resCategory === 1, value: 'open',
          atClick: (data: ResourceModel) => {
            onDblClickRow(data)
          }},
        {label: '删除',elType: 'button', value: 'delete',  confirm: {title: '您确定要删除吗？', atConfirm: (data: ResourceModel) => onDeleteFile(data)}}
      ]
    }
  }
})

let listResStateTimeout = null

const onShowSearch = () => {
  showSearch.value = !showSearch.value
  tableDataRef.value.onWindowResize()
}

const onBatchSaveFile = (files: ResourceModel[]) => {
  getFileList(table.paging.pageIndex)
}

const onCreateFolderSuccess = (folder: ResourceModel) => {
  getFileList(table.paging.pageIndex)
}

const onOpenFolderModal = (folder: ResourceModel = null) => {
  folderModalRef.value.onShowModel(search.formData.deptId)
}

const onOpenFileModal = (file: ResourceModel = null) => {
  fileModalRef.value.onShowModel(search.formData.deptId)
}

const getFileList = async (pageIndex: number = 1) => {
  isLoading.value = true
  const res = await ResourceApi.listFile(selectFolderId.value, search.formData.deptId, search.formData.searchKey, pageIndex, table.paging.pageSize)
  table.data = res.data
  table.paging = Object.assign({}, table.paging, {pageIndex: res.pageIndex, total: res.total})
  isLoading.value = false
  const noCompleteList = res.data.filter(item => item.resCategory === 2 &&  [1,2].includes(+item.resState))
  if (noCompleteList?.length && !listResStateTimeout) {
    listResStateTimeout = setTimeout(() => {
      getFileList(table.paging.pageIndex)
    }, 7000)
  } else {
    if (listResStateTimeout) {
      clearTimeout(listResStateTimeout)
      listResStateTimeout = null
    }
  }
}

onBeforeUnmount(() => {
  if (listResStateTimeout) {
    clearTimeout(listResStateTimeout)
    listResStateTimeout = null
  }
})

const selectCurrentFile = async (fileId: string) => {
  if (!fileId) {
    return
  }
  ResourceApi.selectFileById(fileId).then((file: ResourceModel) => {
    console.log('select folder:::', file)
    selectFolder.value = file
    let parentPath = file.parentIdPath;
    if (!!parentPath) {
      if (parentPath.startsWith("/")) {
        parentPath = parentPath.substring(1)
      }
      const filePaths =parentPath.split("/")
      filePaths.forEach((path, index) => {
        const pathArr = path.split(":")
        folderArr.value.push({
          name: pathArr[1],
          id: pathArr[0]
        })
      })
    }
    folderArr.value.push({
      name: file.resName,
      id: file.resId
    })
  })
}

const onPageChange = (pageIndex: number) => {
  if (pageIndex != paging.value.pageIndex) {
    getFileList(pageIndex);
  }
}

const onDeleteFile = (file: ResourceModel) => {
  ResourceApi.deleteTemplate(file.resId).then((res) => {
    if (res) {
      ElMessage.success({
        message: file.resCategory == 1 ? "目录删除成功" : "文件删除成功",
        showClose: true
      })
      getFileList( 1)
    }
  })
}

const onDblClickRow = (row: ResourceModel) => {
  console.log('on dbl click:::', row)
  if (row.resCategory === 2) {
    return
  }
  if (selectFolderId.value) {
    folderArr.value.push({
      name: row.resName,
      id: row.resId
    })
  }
  router.push({name: 'Resource', query: {folderId: row.resId}})
}

const onOpenFolder = (folder) => {
  router.push({name: 'Resource', query: {folderId: folder.id}})
}

watch(() => route.query.folderId, () => {
  folderArr.value = [{
    name: '资源管理',
    id: null
  }]
  selectCurrentFile(route.query.folderId as string)
  selectFolderId.value = route.query.folderId as string
  getFileList( 1)
}, {immediate: true})
</script>
<style scoped lang="scss">
.yy-file {
  &-list {
    user-select: none;
    flex: 1;
    min-width: 0;
    display: flex;
    flex-direction: column;
    height: 100%;
    &-action-item {
      margin: 0 2px;
    }
    &-header {
      border-bottom: 1px solid var(--el-border-color);
    }
  }
}
</style>
